import { AdvisorItem } from '@/types/common'
import { ChangeEvent } from 'react'
import { GradeSelect, BaseSelect } from '@/components'
import { SelectChangeEvent } from '@mui/material'
import { AdvisorTypeMap, LiftStatusList } from '@/store/constant'
import { LiftStatusEnum } from '@/types/enum'
import { SET_SNACKBAR } from '@/store/actions'
import { editAdvisor } from '@/api/index'
type Props = {
  row: AdvisorItem
  refresh: () => void
  renderTrigger?: (props: any) => React.ReactNode
}

const InputConfig = [
  { label: '培训开始', key: 'training_date' },
  { label: '考核开始', key: 'examine_date' },
  { label: '转正开始', key: 'work_date' }
]

const getFormData = (row: AdvisorItem) => {
  const { train } = row
  return {
    ...mapValues(keyBy(InputConfig, 'key'), (_v: any, k: string) => get(train, k, '')),
    ...pick(row, ['grade', 'type']),
    init_grade: train.init_grade,
    lift_status: row.is_down ? LiftStatusEnum.Down : row.is_up ? LiftStatusEnum.Up : LiftStatusEnum.Normal
  }
}
const UpdateAdvisorButton = ({ row, refresh, renderTrigger }: Props) => {
  const theme = useTheme()
  const dispatch = useDispatch()
  const [open, setOpen] = useState(false)
  const [formData, setFormData] = useState(getFormData(row))
  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }

  const dateLimit = useMemo(() => {
    const today = dayjs()
    // after today & every Monday
    const training_date = formData.examine_date && {
      ...mapValues({ min: 28, max: 14 }, (v: number) => dayjs(formData.examine_date).subtract(v, 'd').format('YYYY-MM-DD')),
      step: 1
    }
    const examine_date = {
      min: dayjs(Math.max(dayjs(formData.training_date).add(14, 'd').valueOf(), today))
        .day(1)
        .format('YYYY-MM-DD'),
      step: 7
    }
    const work_date = formData.examine_date && {
      min: dayjs(formData.examine_date).add(14, 'd').day(1).format('YYYY-MM-DD'),
      step: 14
    }
    return {
      training_date,
      examine_date,
      work_date
    }
  }, [pick(formData, ['examine_date', 'training_date', 'work_date'])])

  const handleChange = (key: string) => (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | SelectChangeEvent) => {
    const value = e.target.value
    setFormData({ ...formData, [key]: value })
  }
  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))

  const { runAsync, loading } = useRequest(editAdvisor, {
    manual: true,
    onFinally(_params, _data, error) {
      dispatch({
        type: SET_SNACKBAR,
        payload: { children: `操作${error ? '失败: ' + error.message : '成功'}`, severity: error ? 'error' : 'success' }
      })
      handleClose()
      refresh()
    }
  })

  useEffect(() => {
    setFormData(getFormData(row))
  }, [row])

  const handleSubmit = async () => {
    const data = {
      advisor_id: row.advisor_id,
      ...pick(formData, ['grade', 'type']),
      is_up: Number(formData.lift_status === LiftStatusEnum.Up),
      is_down: Number(formData.lift_status === LiftStatusEnum.Down),
      train: {
        ...row.train,
        ...pick(formData, [...map(InputConfig, (v: { key: any }) => v.key), 'init_grade'])
      }
    }
    await runAsync(data)
  }
  return (
    <>
      {renderTrigger ? (
        renderTrigger({ onClick: handleOpen })
      ) : (
        <Button onClick={handleOpen} variant="outlined" size="small" color="secondary">
          Click
        </Button>
      )}
      <Dialog fullWidth maxWidth="xs" fullScreen={fullScreen} open={open} onClose={handleClose}>
        <DialogTitle fontSize="1rem">编辑</DialogTitle>
        <DialogContent>
          <Stack spacing={3} direction="column" padding={2}>
            <Divider>
              <Chip variant="outlined" color="secondary" label="当前职级" size="small" />
            </Divider>
            <GradeSelect value={formData.grade} onChange={handleChange('grade')} />
            <BaseSelect
              options={LiftStatusList}
              id="lift_status"
              value={formData.lift_status}
              label="升降级状态"
              onChange={handleChange('lift_status')}
            />
            <Divider>
              <Chip variant="outlined" color="secondary" label="日期" size="small" />
            </Divider>
            {InputConfig.map((item) => {
              return (
                <TextField
                  key={item.key}
                  required
                  value={formData[item.key]}
                  fullWidth
                  margin="dense"
                  type="date"
                  label={item.label}
                  onChange={handleChange(item.key)}
                  inputProps={get(dateLimit, [item.key], {})}
                />
              )
            })}
            <Divider>
              <Chip variant="outlined" color="secondary" label="转正初始职级" size="small" />
            </Divider>
            <GradeSelect value={formData.init_grade} onChange={handleChange('init_grade')} />
            <Divider>
              <Chip variant="outlined" color="secondary" label="顾问类型" size="small" />
            </Divider>
            <BaseSelect
              options={toPairs(AdvisorTypeMap).map(([value, label]: string[]) => ({ value: Number(value), label }))}
              id="type"
              value={formData.type}
              label="顾问类型"
              onChange={handleChange('type')}
            />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            Cancel
          </Button>
          <LoadingButton variant="contained" color="secondary" loading={loading} onClick={handleSubmit}>
            应用
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default memo(UpdateAdvisorButton)
